import * as cc from 'cc';

export class BattleUnit {
    health: number;
    attackPower: number;
    defense: number;

    event: cc.EventTarget = new cc.EventTarget();

    constructor(health: number, attackPower: number, defense: number) {
        this.health = health;
        this.attackPower = attackPower;
        this.defense = defense;
    }

    takeDamage(damage: number) {
        if (!this.checkAlive()) {
            console.warn('Unit is already dead.');
            return this.health;
        }
        this.health -= Math.max(1, damage - this.defense);
        if (this.health < 0) {
            this.health = 0;
            this.die();
        }
        return this.health;
    }

    checkAlive(): boolean {
        return this.health > 0;
    }

    die() {
        this.event.emit('die');
    }
}
